/**
 * Copyright:Copyright(c)2014-2017
 * Company:厦门市易致达物联网科技有限公司
 *
 * @version 1.0
 */
package shop.controller.front.order;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import shop.core.FrontBaseController;
import shop.core.Services;
import shop.core.common.bean.JSONResult;
import shop.services.front.order.OrderService;
import shop.services.front.order.bean.Order;
import shop.services.front.orderdetail.OrderdetailService;
import shop.services.front.orderdetail.bean.Orderdetail;
import shop.services.front.record.RecordService;
import shop.services.front.record.bean.Record;
import shop.services.front.voucherhave.VoucherhaveService;
import shop.services.front.voucherhave.bean.Voucherhave;
import shop.services.manage.system.bean.User;
import shop.services.manage.system.impl.UserService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.List;

/**
 * @类名称：OrderController
 * @创建人：Wzl
 * @创建时间：2017-09-20 下午15:48:44
 * @版本号：1.0
 * @描述：订单
 */
@Controller
@RequestMapping("/front/order/")
public class OrderController extends FrontBaseController<Order> {
    private final static String RECORT_TYANSTYPE_CASH = "1";
    private final static String RECORT_TYANSTYPE_BROKERAGE= "2";
    @Resource
    private OrderService orderService;
    @Resource
    private OrderdetailService orderdetailService;
    @Resource
    private VoucherhaveService voucherhaveService;
    @Resource
    private UserService userService;
    @Resource
    private RecordService recordService;

    @Override
    public Services<Order> getService() {
        return orderService;
    }


    /**
     * 跳转到订单列表页面
     *
     * @return
     */
    @RequestMapping("toOrderList")
    public String toOrderList() {
        return "/front/order/allOrder";
    }

    /**
     * 跳转到订单详情页面（个人中心入口）
     *
     * @return
     */
    @RequestMapping("toOrderDetail")
    public String toOrderDetail() {
        return "/front/order/orderDetail";
    }

    /**
     * 跳转到订单详情页面（购物车入口）
     *
     * @return
     */
    @RequestMapping("toCartOrderDetail")
    public String toCartOrderDetail() {
        return "/front/order/cartOrderDetail";
    }

    /**
     * 跳转到用户礼卷列表页面
     *
     * @return
     */
    @RequestMapping("toVoucherList")
    public String toVoucherList() {
        return "/front/order/selectCard";
    }

    /**
     * 跳转到活动报名页面
     *
     * @return
     */
    @RequestMapping("toJoinActivity")
    public String toJoinActivity() {
        return "/front/order/joinActivity";
    }

    /**
     * 跳转到充值页面
     *
     * @return
     */
    @RequestMapping("toRecharge")
    public String toRecharge() {
        return "/front/order/accountMoney";
    }

    /**
     * 查询订单列表
     * @param order
     * @return orderList
     */
    @RequestMapping(value = "selectOrderList", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult selectOrderList(Order order) {
        JSONResult jsonResult = new JSONResult();
        List<Order> orderList = orderService.selectList(order);//查询用户订单列表
        for (int i = 0; i < orderList.size(); i++) {
            Order orderInfo = orderList.get(i);
            Orderdetail orderdetail = new Orderdetail();
            orderdetail.setOrderID(orderInfo.getId());
            orderList.get(i).setOrderdetails(orderdetailService.selectOrderDetailList(orderdetail));//添加订单详情
        }
        jsonResult.setData(orderList);
        jsonResult.setSuccess(true);
        return jsonResult;
    }

    /**
     * 查询订单详情（个人中心入口）
     * @return
     */
    @RequestMapping(value = "selectOrderDetail", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult selectOrderDetail(Orderdetail orderdetail) {
        Orderdetail orderdetailInfo = new Orderdetail();
        orderdetailInfo.setOrderID(orderdetail.getOrderID());
        List<Orderdetail> rsList = orderdetailService.selectOrderDetailList(orderdetailInfo);
        return new JSONResult(rsList, true);
    }

    /**
     * 查询用户订单地址
     * @param order
     * @return
     */
    @RequestMapping(value = "selectOrderAddress", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult selectOrderAddress(Order order) {
        order = orderService.selectOne(order);
        jsonResult = new JSONResult();
        jsonResult.setData(order);
        return jsonResult;
    }

    /**
     * 余额抵扣
     *
     * @param order
     * @return
     */
    @RequestMapping(value = "deductionOrder", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult deductionOrder(HttpSession session, Order order) {
        User user = (User) session.getAttribute("userInfo");
        order.setUserID(user.getId());
        order.setStatus("pass");
        int orderID = orderService.insert(order);
        //买家上级数据更新
        if (!"0".equals(user.getPid())) {
            //上级返利
            User supUser = new User();
            supUser.setId(user.getPid());
            supUser = userService.selectOne(supUser);
            logger.debug("返利比例" + order.getPercent());
            BigDecimal brokerage = order.getPtotal().multiply(new BigDecimal(order.getPercent()));
            brokerage = brokerage.setScale(2, BigDecimal.ROUND_HALF_UP);
            logger.debug("返利金额" + brokerage);
            supUser.setIncome(supUser.getIncome().add(brokerage));
            userService.update(supUser);
            //上级交易记录
            Record recordInfo = new Record();
            recordInfo.setUserID(supUser.getId());
            recordInfo.setTransType(RECORT_TYANSTYPE_BROKERAGE);
            recordInfo.setTransID(order.getId());
            recordInfo.setMoney(brokerage);
            recordService.insert(recordInfo);
        }
        return new JSONResult<>(orderID, true);
    }

    @Override
    public JSONResult deleteJson(HttpServletRequest request, Order order) throws Exception {
        if (!"0".equals(order.getVoucherID())) {
            String[] voucherIDs = order.getVoucherID().split(",");
            for(int i=0;i<voucherIDs.length;i++){
                Voucherhave voucherhave = new Voucherhave();
                voucherhave.setUserID(order.getUserID());
                voucherhave.setVoucherID(voucherIDs[i]);
                voucherhave = voucherhaveService.selectOne(voucherhave);
                if(voucherhave!=null){
                    voucherhave.setAmount(voucherhave.getAmount() + 1);
                    voucherhaveService.update(voucherhave);
                }else{
                    Voucherhave oneVoucherhave=new Voucherhave();
                    oneVoucherhave.setUserID(order.getUserID());
                    oneVoucherhave.setVoucherID(voucherIDs[i]);
                    voucherhaveService.insert(oneVoucherhave);
                }
            }
        }
        return super.deleteJson(request, order);
    }
}
